<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8"/>
		<meta name="screen-orientation" content="portrait">
		<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>image upload</title>
		<link rel="stylesheet" type="text/css" href="main.css" />
	</head>
	<body>
		<div class="image-warpper">
			<img id="preview-image" src="icon_add.png" class="hide">
			<input type="file" class="file-input" name="file-input" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" value="">
		</div>
	</body>
	<script src="jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		$(".file-input").on("change", function(){
			var $preview = $(this).siblings("img");
		    var files = !!this.files ? this.files : [];
		    if (!files.length || !window.FileReader) {
//		    	EMS.alert("浏览器不支持HTML5");
		    	return false;
		    };
		    if (/image\/\w+/.test(files[0].type)){
		    	var reader = new FileReader();
		        reader.readAsDataURL(files[0]);
		        var fileType = files[0].type;
		        reader.onloadend = function(){
		        	preview($preview,reader.result);
		        	compress(reader.result,fileType);
		        }
		        
		    }else{
		    	console.log("不是图片");
		    }
		});
		
		
		function preview($preview, image){
			$preview.attr("src",image).show().removeClass("hide");
      		$preview.closest('.image-warpper').css({'background':'#f5f5f5','border':'2px dashed #ccc'})
		}
		
		function compress(uncompressed, fileType){
			var image = new Image();
            image.src = uncompressed;
            image.onload = function(){
            	var canvas = document.createElement('canvas');
            	//如果图片大于四百万像素，计算压缩比并将大小压至400万以下
		        var ratio;
		        if ((ratio = this.width * this.height / 4000000)>1) {
		            ratio = Math.sqrt(ratio);
		            this.width /= ratio;
		            this.height /= ratio;
		        }else {
		            ratio = 1;
		        }
		
		        canvas.width = this.width;
		        canvas.height = this.height;
		        
            	var ctx = canvas.getContext('2d');
            	ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
            	var newImage = canvas.toDataURL(fileType, 0.7);
            	//转化成二进制文件数据并存入 FormData
            	var fd = new FormData();
				var blob = dataURItoBlob(newImage);
				fd.append('file', blob);
				console.log(blob);
        	}
		}
		
		//base64 转 二进制文件
		function dataURItoBlob(dataURI) {
		    var byteString = atob(dataURI.split(',')[1]);
		    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
		    var ab = new ArrayBuffer(byteString.length);
		    var ia = new Uint8Array(ab);
		    for (var i = 0; i < byteString.length; i++) {
		        ia[i] = byteString.charCodeAt(i);
		    }
		    return new Blob([ab], {type: mimeString});
		}
		
	</script>

</html>
